package org.lex.swing.widgets;

import java.io.OutputStream;
import java.io.Writer;

public class OutputStreamTextArea extends EnhancedTextArea {
	private Writer writer = null;
	private OutputStream out = null;

	public OutputStreamTextArea() {
		super();
	}

	/*
	 * public api
	 */
	public synchronized void append(String str) {
		super.append(str);
		if (true == this.getAutoScrollAction().isSelected())
			moveCaretToEnd();
	}

	public OutputStream getOutputStream() {
		if (null == this.out) {
			out = new OutputStream() {
				private OutputStreamTextArea adaptee = OutputStreamTextArea.this;

				@Override
				public void write(byte[] b, int off, int len) {
					adaptee.write(b, off, len);
				}

				@Override
				public void write(byte[] b) {
					this.write(b, 0, b.length);
				}

				@Override
				public void write(int b) {
					adaptee.write(b);
				}
			};
		}
		return this.out;
	}

	public Writer getWriter() {
		if (null == this.writer) {
			this.writer = new Writer() {
				private OutputStreamTextArea textArea = OutputStreamTextArea.this;

				@Override
				public void write(int c) {
					textArea.write(c);
				}

				@Override
				public void write(char[] cbuf, int off, int len) {
					textArea.write(cbuf, off, len);
				}

				public void write(String str) {
					textArea.append(str);
				}

				@Override
				public void write(String str, int off, int len) {
					textArea.append(str.substring(off, off + len));
				}

				@Override
				public void close() {
				}

				@Override
				public void flush() {
				}
			};
		}
		return this.writer;
	}

	private void write(int ch) {
		this.append(String.valueOf((char) ch));
	}

	private void write(byte[] buf, int offset, int length) {
		this.append(new String(buf, offset, length));
	}

	private void write(char[] cbuf, int offset, int length) {
		this.append(new String(cbuf, offset, length));
	}
}
